import os
from config import config
import json
import time
import datetime
from event import Event

scriptList = []


def load():
    global scriptList
    filePath = config.SCRIPT_LIST_PATH
    if not os.path.exists(filePath):
        return

    with open(filePath, 'r', encoding='utf8') as file:
        content = file.read()
        if len(content) == 0:
            return

        scriptList = json.loads(content)


def refresh():
    with open(config.SCRIPT_LIST_PATH, 'w', encoding='utf-8') as file:
        file.write(json.dumps(scriptList))


def reset(newList=None):
    global scriptList
    if newList:
        scriptList = newList

    with open(config.SCRIPT_LIST_PATH, 'w', encoding='utf-8') as file:
        file.write(json.dumps(scriptList))


def curId():
    global scriptList
    currentId = 0
    for script in scriptList:
        if script['id'] >= currentId:
            currentId = script['id']

    return currentId


def add(script):
    global scriptList

    timestamp = time.time()  # 当前时间戳
    curTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
    script['id'] = curId() + 1
    script['updated_at'] = curTime
    script['created_at'] = curTime
    scriptList.append(script)
    Event.dispatch('script_add', script)
    refresh()


def getById(Id):
    global scriptList
    for script in scriptList:
        if script['id'] == Id:
            return script

    return None


def getIdxById(Id):
    global scriptList
    for key, script in enumerate(scriptList):
        if script['id'] == Id:
            return key

    return None


def update(script):
    global scriptList

    timestamp = time.time()  # 当前时间戳
    curTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
    script['updated_at'] = curTime

    idx = getIdxById(script['id'])
    scriptList[idx] = script
    Event.dispatch('script_update', script["id"], script)
    refresh()


def removeById(Id):
    global scriptList
    script = getById(Id)
    remove(script)


def remove(script):
    global scriptList
    if script is None or (not script):
        return

    if script not in scriptList:
        return

    scriptList.remove(script)
    Event.dispatch('remove', script)
    refresh()


def scriptNames():
    global scriptList
    names = []
    for script in scriptList:
        names.append(script['name'])

    return names


load()
